import { sm4 } from 'sm-crypto'

// 文本加密
const DEFAULT_KEY = 'cda4442f102f6396eea76902e37ad7cb'
const DEFAULT_IV = '8bd8a83221742111c7532b7275a7fe9c'
export const encrypt = (str: string) => {
    if (!str) {
        return ''
    }
    const encryptStr = sm4.encrypt(str, DEFAULT_KEY, {
        iv: DEFAULT_IV,
        mode: 'cbc',
        padding: 'pkcs#7'
    })
    return 'ENC(' + encryptStr + ')'
}

// 文本解密
export const decrypt = (str: string) => {
    if (!str) {
        return ''
    }
    if (str.indexOf('ENC(') === -1) {
        return str
    }
    const str_ = str.replace('ENC(', '').replace(')', '').replace(' ', '')
    try {
        const decryptStr = sm4.decrypt(str_, DEFAULT_KEY, {
            iv: DEFAULT_IV,
            mode: 'cbc',
            padding: 'pkcs#7'
        })
        return decryptStr
    } catch (error) {
        return '解密失败！'
    }
}